/**
 * @typedef {Object} vecodeConfig
 * @prop {string} [url=''] 发送的url
 * @prop {string} [before=获取验证码] 发送前的文字
 * @prop {string} [sended={time}s] 发送后的文字
 */

export default function (params = {}) {
	const vecodeConfig = {
		url: "/api/sendCode",
		before: "获取验证码",
		sended: "{time}s",
		type: 1,
		...params,
	}
	return {
		data() {
			return {
				veCodeTime: 60,
			}
		},
		computed: {
			veCodeText() {
				return vecodeConfig[this.veCodeTime < 60 ? "sended" : "before"].replace("{time}", this.veCodeTime)
			},
		},
		methods: {
			async sendCode(phone) {
				if (this.veCodeTime < 60) {
					return
				}
				if (phone[0] != "1" || phone.length != 11) {
					this.showMessage.error("请输入正确的手机号")
					return
				}
				this.veCodeTime--
				let timer = setInterval(() => {
					this.veCodeTime--
					if (this.veCodeTime <= 0) {
						clearInterval(timer)
						this.veCodeTime = 60
					}
				}, 1000)
				try {
					await this.$http({
						url: vecodeConfig.url,
						method: "post",
						data: {
							mobile: phone,
							type: vecodeConfig.type,
						},
					})
					this.showMessage.success("发送成功")
				} catch (error) {
					this.showMessage.error(error)
					clearInterval(timer)
					setTimeout(() => {
						this.veCodeTime = 60
					}, 500)
				}
			},
		},
	}
}
